package com.flink.watermark;

import com.flink.func.WaterSensorMapFunction;
import com.flink.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;

/**
 * WindowDelayDemo
 *
 * @author caizhiyang
 * @since 2024-02-28
 */
public class WindowDelayDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env.socketTextStream("localhost", 7777)
                .map(new WaterSensorMapFunction())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                // 设置水位线乱序 延迟3秒
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                //设置水位线提取字段
                                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                                    @Override
                                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                        System.out.println("数据:" + element);
                                        return element.getTs() * 1000;
                                    }
                                })
                ).keyBy(w -> w.getId())
                //事件时间语义 滚动窗口 窗口大小10秒
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                //窗口延迟时间 2秒
                .allowedLateness(Time.seconds(2))
                .sum("vc")
                .print();
        env.execute();
    }
}
